//
//  DownloadOperation.m
//  仿SDWebImage
//
//  Created by WangBiao on 16/9/18.
//  Copyright © 2016年 lsrain. All rights reserved.
//

#import "DownloadOperation.h"
#import "NSString+path.h"

@implementation DownloadOperation

+ (instancetype)downloadImageWithURLString:(NSString *)URLStirng finishBlcok:(void (^)(UIImage *))finishBlock{
    DownloadOperation *download = [[DownloadOperation alloc] init];
    
    download.URLString = URLStirng;
    download.finishBlock = finishBlock;
    
    return download;
}

//需求，将下载好的图片存入沙盒
- (void)main{
    
    //模拟网络延迟
    [NSThread sleepForTimeInterval:1.0];
    
    NSURL *URL = [NSURL URLWithString:self.URLString];
    NSData *data = [NSData dataWithContentsOfURL:URL];
    UIImage *img = [UIImage imageWithData:data];
    
    if (img) {
        [data writeToFile:[self.URLString appendCache]  atomically:YES];
    }
    
    if (self.cancelled) {
        NSLog(@"取消线程操作：%@", [NSThread currentThread]);
        return;
    }
    
    //断言
    NSAssert(self.finishBlock != nil, @"数据回调不能为空");
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
        NSLog(@"下载完成...");
        //回到单例block
        self.finishBlock(img);
    }];
   
}
@end
